// 坐标问题
// https://blog.csdn.net/wangfengquan_/article/details/114575342?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1.pc_relevant_aa&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1.pc_relevant_aa&utm_relevant_index=2

import { Vector as VectorSource } from 'ol/source';
import { Vector as VectorLayer } from 'ol/layer';
import { getStyle } from './style'
import { layerConfig } from '@/config/config'
import WFS from 'ol/format/WFS';
import GML from 'ol/format/GML';
import { Feature } from 'ol';
import { transactGeo } from '@/api/geoApi'
import { Message } from 'element-ui';

export const addLayer = new VectorLayer({
    name: 'add',
    source: new VectorSource(),
    style: getStyle('add', false, null),
    zIndex: 4
});

// type: 增加删除修改
// layer: 图层
// feature: 要素
export const transact = async (type, layer, feature) => {
    let reqData, insertF, updateF, deleteF = null;

    // 经纬度换位
    feature.getGeometry().applyTransform((flatCoordinates, flatCoordinates2, stride) => {
        for (var j = 0; j < flatCoordinates.length; j += stride) {
            var y = flatCoordinates[j];
            var x = flatCoordinates[j + 1];
            flatCoordinates[j] = x;
            flatCoordinates[j + 1] = y;
        }
    })

    let f = new Feature()
    f.setGeometryName('geom')
    f.setGeometry(feature.getGeometry())
    f.setProperties(feature.getProperties())
    console.log(f.getGeometry())

    switch (type) {
        case 'insert':
            insertF = [f]
            break;
        case 'update':
            // id
            f.setId(feature.getId())
            updateF = [f]
            break;
        case 'delete':
            f.setId(feature.getId())
            deleteF = [f]
            break;
    }

    let formatWFS = new WFS();
    let wt = formatWFS.writeTransaction(insertF, updateF, deleteF, {
        srsName: "EPSG:4326", //坐标系
        featureNS: layerConfig.featureNS, // 注意这个值必须为创建工作区时的命名空间URI
        featureType: layer, //所要访问的图层
    });

    reqData = new XMLSerializer().serializeToString(wt)

    let res = await transactGeo(reqData)
    if (res.status === 200) {
        let text = type === 'insert' ? '新增' : type === 'update' ? '编辑' : '删除'
        Message.success(`${text}成功`);
        return
    } else {
        Message.error('查询图层失败');
        return
    }

    // await fetch(layerConfig.baseUrl, {
    //     method: "post",
    //     contentType: 'text/xml',
    //     body: reqData
    // }).then((response) => {

    // }).then((json) => {
    // });
}